<!--
 * @Author: jhw jiaxianshengye@gmail.com
 * @LastEditTime: 2025-07-31 16:37:10
 * @LastEditors: jhw
 * @Description: 文件描述
-->
<template>
  <div ref="container" class="lazy-chart">
    {{ num }}
    <div ref="chartEl" class="chart"></div>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, onUnmounted, nextTick } from 'vue'
import echarts from '@/plugins/index'
const props = defineProps({
  options: {
    default: {},
  },
  type: {},
  num: {},
})

const container = ref(null)
const chartEl = ref(null)
const isLoaded = ref(false)
let chartInstance: any

const initChart = () => {
  nextTick(() => {
    if (!chartEl.value) return

    chartInstance = echarts.init(chartEl.value)
    chartInstance.setOption(props.options)

    // 添加resize监听
    const resizeHandler = () => chartInstance.resize()
    window.addEventListener('resize', resizeHandler, { passive: true })

    isLoaded.value = true

    // 清理函数
    return () => {
      window.removeEventListener('resize', resizeHandler)
      chartInstance.dispose()
    }
  })
}

onMounted(() => {
  console.log(`Chart ${props.num} entered viewport`)
  initChart()
})

onUnmounted(() => {
  chartInstance?.dispose()
})
</script>
<style>
.lazy-chart {
  width: 100%; /* 更灵活的宽度 */
  height: 400px; /* 更合理的高度 */
  border: 1px solid black;
  margin-bottom: 20px;
}
.chart {
  height: 400px; /* 必须设置固定高度 */
}
</style>
